import React, { useState, useCallback, useEffect } from 'react';
import Cropper from 'react-easy-crop';
import { Card, Upload, Button, Slider, Form, InputNumber, Row, Col, message, Image, Space, List, Typography, Switch, Modal } from 'antd';
import { UploadOutlined, DownloadOutlined, RotateLeftOutlined, RotateRightOutlined, ZoomInOutlined, ZoomOutOutlined, DeleteOutlined, EnvironmentOutlined } from '@ant-design/icons';
import type { RcFile, UploadProps } from 'antd/es/upload';
import type { Area } from 'react-easy-crop';
import { fileSystemService, dataUrlToUint8Array } from '../services/fileSystemService';

const { Title, Text } = Typography;

interface ImageFile {
  id: string;
  file: RcFile;
  url: string;
  name: string;
}

interface CropSettings {
  width: number;
  height: number;
  aspectRatio: number | null;
  usePercentage: boolean;
  widthPercentage: number;
  heightPercentage: number;
}

const BatchImageCropper: React.FC = () => {
  const [images, setImages] = useState<ImageFile[]>([]);
  const [activeImageId, setActiveImageId] = useState<string | null>(null);
  const [crop, setCrop] = useState({ x: 0, y: 0 });
  const [zoom, setZoom] = useState(1);
  const [rotation, setRotation] = useState(0);
  const [croppedAreaPixels, setCroppedAreaPixels] = useState<Area | null>(null);
  const [cropSettings, setCropSettings] = useState<CropSettings>({
    width: 300,
    height: 300,
    aspectRatio: 1,
    usePercentage: false,
    widthPercentage: 50,
    heightPercentage: 50
  });
  const [croppedImages, setCroppedImages] = useState<{[key: string]: string}>({});
  const [savePath, setSavePath] = useState<string>('');
  const [isTauriEnvironment, setIsTauriEnvironment] = useState(false);

  // 初始化时检查环境并获取默认下载文件夹
  useEffect(() => {
    const initEnvironment = async () => {
      try {
        const isTauri = fileSystemService.isTauriEnvironment();
        setIsTauriEnvironment(isTauri);
        
        if (isTauri) {
          // 在Tauri环境中，尝试获取系统下载文件夹
          const downloadFolder = await fileSystemService.getDownloadFolder();
          setSavePath(downloadFolder);
        } else {
          // 在浏览器环境中，使用默认值
          setSavePath('浏览器下载文件夹');
        }
      } catch (error) {
        console.error('初始化环境失败:', error);
        setSavePath('下载文件夹');
      }
    };
    
    initEnvironment();
  }, []);

  const activeImage = images.find(img => img.id === activeImageId) || null;

  // 简化handleUpload，使用processFile处理单个文件
  const handleUpload: UploadProps['beforeUpload'] = (file) => {
    processFile(file);
    return false;
  };

  const processFile = (file: RcFile) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('只能上传 JPG/PNG 格式的图片!');
      return false;
    }
    
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片大小不能超过 2MB!');
      return false;
    }
    
    // 检查文件是否已存在（通过uid和name双重检查）
    if (images.some(img => img.file.uid === file.uid || img.name === file.name)) {
      // 文件已存在，跳过
      return false;
    }
    
    const reader = new FileReader();
    reader.onload = (e) => {
      const newImage: ImageFile = {
        id: `${file.uid}`,
        file,
        url: e.target?.result as string,
        name: file.name
      };
      
      setImages(prev => [...prev, newImage]);
      
      // 如果是第一张图片，设置为活动图片
      if (images.length === 0) {
        setActiveImageId(newImage.id);
      }
    };
    reader.readAsDataURL(file);
    
    return false;
  };

  const handleUploadMultiple: UploadProps['beforeUpload'] = (_file, fileList) => {
    // 处理多个文件上传
    const newFiles = fileList.filter(f => !images.some(img => img.file.uid === f.uid || img.name === f.name));
    newFiles.forEach(f => processFile(f));
    return false;
  };

  const removeImage = (id: string) => {
    // 使用函数式更新确保获取到最新的images状态
    setImages(prevImages => {
      const filteredImages = prevImages.filter(img => img.id !== id);
      
      // 如果删除的是当前活动图片，设置新的活动图片
      if (activeImageId === id) {
        setActiveImageId(filteredImages.length > 0 ? filteredImages[0].id : null);
      }
      
      return filteredImages;
    });
    
    setCroppedImages(prev => {
      const newCropped = { ...prev };
      delete newCropped[id];
      return newCropped;
    });
  };

  // 添加裁剪框大小调整功能
  const [cropSize, setCropSize] = useState({ width: 300, height: 300 });

  const onCropComplete = useCallback((_croppedArea: Area, croppedAreaPixels: Area) => {
    setCroppedAreaPixels(croppedAreaPixels);
  }, []);

  // 处理裁剪框宽度变化
  const handleCropWidthChange = (value: number | null) => {
    if (value !== null) {
      setCropSize(prev => {
        const newSize = { ...prev, width: value };
        // 重置裁剪位置以确保在视图中
        setCrop({ x: 0, y: 0 });
        return newSize;
      });
      // 更新裁剪设置
      setCropSettings(prev => ({ ...prev, width: value }));
    }
  };

  // 处理裁剪框高度变化
  const handleCropHeightChange = (value: number | null) => {
    if (value !== null) {
      setCropSize(prev => {
        const newSize = { ...prev, height: value };
        // 重置裁剪位置以确保在视图中
        setCrop({ x: 0, y: 0 });
        return newSize;
      });
      // 更新裁剪设置
      setCropSettings(prev => ({ ...prev, height: value }));
    }
  };

  // 从预览区直接修改裁剪尺寸的逻辑已经在handleCropWidthChange和handleCropHeightChange中实现

  const createImage = (url: string): Promise<HTMLImageElement> =>
    new Promise((resolve, reject) => {
      const image = new window.Image();
      image.addEventListener('load', () => resolve(image));
      image.addEventListener('error', (error: ErrorEvent) => reject(error));
      image.setAttribute('crossOrigin', 'anonymous');
      image.src = url;
    });

  const getCroppedImg = async (imageSrc: string, pixelCrop: Area, rotation = 0, format = 'image/jpeg'): Promise<string> => {
    const image = await createImage(imageSrc);
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');

    if (!ctx) {
      throw new Error('无法创建 canvas 上下文');
    }

    const maxSize = Math.max(image.width, image.height);
    const safeArea = 2 * ((maxSize / 2) * Math.sqrt(2));

    canvas.width = safeArea;
    canvas.height = safeArea;

    ctx.translate(safeArea / 2, safeArea / 2);
    ctx.rotate((rotation * Math.PI) / 180);
    ctx.translate(-safeArea / 2, -safeArea / 2);

    ctx.drawImage(
      image,
      safeArea / 2 - image.width * 0.5,
      safeArea / 2 - image.height * 0.5
    );

    const data = ctx.getImageData(0, 0, safeArea, safeArea);

    canvas.width = pixelCrop.width;
    canvas.height = pixelCrop.height;

    ctx.putImageData(
      data,
      Math.round(0 - safeArea / 2 + image.width * 0.5 - pixelCrop.x),
      Math.round(0 - safeArea / 2 + image.height * 0.5 - pixelCrop.y)
    );

    // 使用指定的格式返回，默认JPEG质量0.95
    return canvas.toDataURL(format, 0.95);
  };

  const handleCrop = async () => {
    if (!activeImage || !croppedAreaPixels) return;
    
    try {
      // 从文件名获取原始格式
      const fileExtension = activeImage.name.split('.').pop()?.toLowerCase();
      const format = fileExtension === 'png' ? 'image/png' : 'image/jpeg';
      
      const croppedImageUrl = await getCroppedImg(activeImage.url, croppedAreaPixels, rotation, format);
      
      // 保存裁剪结果
      setCroppedImages(prev => ({
        ...prev,
        [activeImage.id]: croppedImageUrl
      }));
      
      message.success(`${activeImage.name} 裁剪成功！`);
    } catch (error) {
      message.error('裁剪图片时出错，请重试');
    }
  };

  const handleBatchCrop = async () => {
    if (images.length === 0) {
      message.warning('请先添加图片');
      return;
    }
    
    let successCount = 0;
    for (const image of images) {
      try {
        // 从文件名获取原始格式
        const fileExtension = image.name.split('.').pop()?.toLowerCase();
        const format = fileExtension === 'png' ? 'image/png' : 'image/jpeg';
        
        const croppedImageUrl = await getCroppedImg(image.url, croppedAreaPixels || { x: 0, y: 0, width: 100, height: 100 }, rotation, format);
        setCroppedImages(prev => ({
          ...prev,
          [image.id]: croppedImageUrl
        }));
        successCount++;
      } catch (error) {
        message.error(`${image.name} 裁剪失败`);
      }
    }
    
    message.success(`批量裁剪完成，成功处理 ${successCount}/${images.length} 张图片`);
  };

  const handleDownload = async (id: string) => {
    const croppedImage = croppedImages[id];
    if (!croppedImage) {
      message.warning('请先裁剪图片');
      return;
    }
    
    try {
      const image = images.find(img => img.id === id);
      const fileExtension = image?.name.split('.').pop()?.toLowerCase() || 'jpeg';
      const fileName = image ? `cropped-${image.name}` : `cropped-image.${fileExtension}`;
      
      if (isTauriEnvironment) {
        // 在Tauri环境中，使用Rust后端API直接保存文件
        const fileData = dataUrlToUint8Array(croppedImage);
        const fullPath = await fileSystemService.saveFileToPath(fileData, fileName, savePath);
        message.success(`图片已保存到：${fullPath}`);
      } else {
        // 在浏览器环境中，使用传统的下载方式
        // 创建链接并设置属性
        const link = document.createElement('a');
        
        // 改进的下载方式，处理不同浏览器的兼容性
        link.download = fileName;
        
        // 对于大型图片或某些浏览器，使用blob方式可能更可靠
        if (croppedImage.startsWith('data:')) {
          // 将data URL转换为Blob
          const byteString = atob(croppedImage.split(',')[1]);
          const mimeString = croppedImage.split(',')[0].split(':')[1].split(';')[0];
          const ab = new ArrayBuffer(byteString.length);
          const ia = new Uint8Array(ab);
          
          for (let i = 0; i < byteString.length; i++) {
            ia[i] = byteString.charCodeAt(i);
          }
          
          const blob = new Blob([ab], { type: mimeString });
          link.href = URL.createObjectURL(blob);
          
          // 下载完成后释放URL对象
          link.onclick = () => {
            setTimeout(() => {
              URL.revokeObjectURL(link.href);
            }, 100);
          };
        } else {
          link.href = croppedImage;
        }
        
        // 使用鼠标事件触发下载，提高兼容性
        const event = new MouseEvent('click', {
          bubbles: true,
          cancelable: true,
          view: window
        });
        
        // 触发下载
        document.body.appendChild(link);
        link.dispatchEvent(event);
        document.body.removeChild(link);
        
        message.success(`图片将下载到浏览器默认的下载文件夹中: ${fileName}`);
      }
    } catch (error) {
      console.error('下载图片时出错:', error);
      message.error(`下载图片时出错: ${error instanceof Error ? error.message : String(error)}`);
    }
  };
  
  const handleSelectSavePath = async () => {
    try {
      if (isTauriEnvironment) {
        // 在Tauri环境中，调用Rust后端API选择文件夹
        const selectedFolder = await fileSystemService.selectFolder();
        setSavePath(selectedFolder);
        message.success(`保存路径已更新为：${selectedFolder}`);
      } else {
        // 在浏览器环境中，显示提示
        Modal.info({
          title: '选择保存路径',
          content: (
            <div>
              <p>在浏览器环境中，图片将下载到浏览器默认的下载文件夹。</p>
              <p>要自定义保存位置，请在桌面应用中运行此程序。</p>
            </div>
          )
        });
      }
    } catch (error) {
      console.error('选择保存路径失败:', error);
      message.error(`选择保存路径失败: ${error instanceof Error ? error.message : String(error)}`);
    }
  };

  const handleDownloadAll = async () => {
    if (Object.keys(croppedImages).length === 0) {
      message.warning('没有可下载的裁剪图片');
      return;
    }
    
    // 显示保存路径提示和确认对话框
    Modal.confirm({
      title: '确认批量下载',
      content: `所有裁剪图片将保存到：${savePath}\n\n确认开始批量下载吗？`,
      onOk: async () => {
        try {
          if (isTauriEnvironment) {
            // 在Tauri环境中，使用Rust后端API批量保存文件
            let successCount = 0;
            
            for (const [id, croppedImage] of Object.entries(croppedImages)) {
              try {
                const image = images.find(img => img.id === id);
                const fileExtension = image?.name.split('.').pop()?.toLowerCase() || 'jpeg';
                const fileName = image ? `cropped-${image.name}` : `cropped-image-${id}.${fileExtension}`;
                
                const fileData = dataUrlToUint8Array(croppedImage);
                await fileSystemService.saveFileToPath(fileData, fileName, savePath);
                successCount++;
              } catch (error) {
                console.error(`保存图片${id}时出错:`, error);
              }
            }
            
            if (successCount > 0) {
              message.success(`${successCount}张图片已成功保存到：${savePath}`);
              if (successCount < Object.keys(croppedImages).length) {
                message.warning(`部分图片保存失败，请检查日志`);
              }
            } else {
              message.error('所有图片保存失败，请检查日志');
            }
          } else {
            // 在浏览器环境中，添加延迟以避免浏览器的下载限制
            const ids = Object.keys(croppedImages);
            let delay = 0;
            
            ids.forEach(id => {
              setTimeout(() => {
                handleDownload(id);
              }, delay);
              
              // 每张图片之间添加100毫秒延迟
              delay += 100;
            });
            
            message.success(`开始下载 ${ids.length} 张图片到浏览器默认下载文件夹`);
          }
        } catch (error) {
          console.error('批量下载图片时出错:', error);
          message.error(`批量下载图片时出错: ${error instanceof Error ? error.message : String(error)}`);
        }
      }
    });
  };

  const handleRotateLeft = () => {
    setRotation(prev => prev - 90);
  };

  const handleRotateRight = () => {
    setRotation(prev => prev + 90);
  };

  const handleZoomIn = () => {
    setZoom(prev => Math.min(prev + 0.1, 3));
  };

  const handleZoomOut = () => {
    setZoom(prev => Math.max(prev - 0.1, 1));
  };

  const handleSettingChange = (field: keyof CropSettings, value: any) => {
    setCropSettings(prev => ({
      ...prev,
      [field]: value
    }));
  };

  const setActiveImage = (id: string) => {
    setActiveImageId(id);
    // 重置裁剪参数
    setCrop({ x: 0, y: 0 });
    setZoom(1);
    setRotation(0);
  };

  return (
    <Card title="批量图片裁剪工具" style={{ width: '100%' }}>
      <div style={{ marginBottom: 16, padding: 10, backgroundColor: '#e6f7ff', border: '1px solid #91d5ff', borderRadius: 4 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 8 }}>
          <Typography.Text strong>
            {isTauriEnvironment 
              ? '图片将保存到指定文件夹，可点击按钮自定义保存位置'
              : '在浏览器环境中，图片将下载到默认下载文件夹'
            }
          </Typography.Text>
          <Button 
            icon={<EnvironmentOutlined />}
            onClick={handleSelectSavePath}
            title="选择保存路径"
            disabled={!isTauriEnvironment}
          >
            选择保存路径
          </Button>
        </div>
        <div style={{ marginTop: 8, fontSize: '14px', color: '#666' }}>
          当前保存路径: <Text type="secondary" ellipsis={{ tooltip: savePath }} style={{ maxWidth: '400px', display: 'inline-block' }}>
            {savePath}
          </Text>
          {!isTauriEnvironment && (
            <Text type="warning" style={{ marginLeft: 8, fontSize: '12px' }}>
              (仅桌面应用支持自定义保存路径)
            </Text>
          )}
        </div>
      </div>
      <Row gutter={[16, 16]}>
        <Col span={12}>
          <Card title="上传图片" size="small">
            <Form layout="vertical">
              <Form.Item label="选择图片">
                <Upload 
                  beforeUpload={handleUpload} 
                  multiple
                  accept=".jpg,.jpeg,.png"
                  showUploadList={false}
                >
                  <Button icon={<UploadOutlined />}>点击上传</Button>
                </Upload>
                <Upload 
                  beforeUpload={handleUploadMultiple} 
                  multiple
                  accept=".jpg,.jpeg,.png"
                  showUploadList={false}
                  style={{ marginTop: 8 }}
                >
                  <Button icon={<UploadOutlined />}>批量上传</Button>
                </Upload>
              </Form.Item>
              
              <Form.Item label="裁剪尺寸设置">
                <Space>
                  <Switch 
                    checked={cropSettings.usePercentage}
                    onChange={(checked) => handleSettingChange('usePercentage', checked)}
                    checkedChildren="百分比" 
                    unCheckedChildren="像素" 
                  />
                  {cropSettings.usePercentage ? (
                    <>
                      <InputNumber 
                        addonBefore="宽" 
                        value={cropSettings.widthPercentage} 
                        onChange={(value) => value && handleSettingChange('widthPercentage', value)} 
                        min={1}
                        max={100}
                        formatter={value => `${value}%`}
                        parser={value => value ? Number(value.replace('%', '')) : 0}
                      />
                      <InputNumber 
                        addonBefore="高" 
                        value={cropSettings.heightPercentage} 
                        onChange={(value) => value && handleSettingChange('heightPercentage', value)} 
                        min={1}
                        max={100}
                        formatter={value => `${value}%`}
                        parser={value => value ? Number(value.replace('%', '')) : 0}
                      />
                    </>
                  ) : (
                    <>
                      <InputNumber 
                        addonBefore="宽度" 
                        value={cropSize.width} 
                        onChange={handleCropWidthChange} 
                        min={50}
                        max={2000}
                      />
                      <InputNumber 
                        addonBefore="高度" 
                        value={cropSize.height} 
                        onChange={handleCropHeightChange} 
                        min={50}
                        max={2000}
                      />
                    </>
                  )}
                </Space>
              </Form.Item>
              
              {activeImage && (
                <>
                  <Form.Item label="缩放">
                    <Slider 
                      min={0.1} 
                      max={3} 
                      step={0.01} 
                      value={zoom} 
                      onChange={setZoom}
                    />
                  </Form.Item>
                  
                  <Form.Item label="旋转">
                    <Slider 
                      min={-180} 
                      max={180} 
                      step={1} 
                      value={rotation} 
                      onChange={setRotation}
                    />
                  </Form.Item>
                  
                  <Space>
                    <Button onClick={handleRotateLeft} icon={<RotateLeftOutlined />}>
                      左转
                    </Button>
                    <Button onClick={handleRotateRight} icon={<RotateRightOutlined />}>
                      右转
                    </Button>
                    <Button onClick={handleZoomOut} icon={<ZoomOutOutlined />}>
                      缩小
                    </Button>
                    <Button onClick={handleZoomIn} icon={<ZoomInOutlined />}>
                      放大
                    </Button>
                    <Button type="primary" onClick={handleCrop}>
                      裁剪当前图片
                    </Button>
                    <Button type="primary" onClick={handleBatchCrop}>
                      批量裁剪
                    </Button>
                  </Space>
                </>
              )}
            </Form>
          </Card>
          
          <Card title="图片列表" size="small" style={{ marginTop: 16 }}>
            <List
              dataSource={images}
              renderItem={item => (
                <List.Item 
                  key={item.id}
                  actions={[
                    <Button 
                      type="link" 
                      size="small" 
                      onClick={() => handleDownload(item.id)}
                      disabled={!croppedImages[item.id]}
                    >
                      下载
                    </Button>,
                    <Button 
                      type="text" 
                      icon={<DeleteOutlined />} 
                      danger 
                      onClick={() => removeImage(item.id)}
                    />
                  ]}
                >
                  <div 
                    style={{ 
                      display: 'flex', 
                      alignItems: 'center', 
                      cursor: 'pointer',
                      backgroundColor: activeImageId === item.id ? '#e6f7ff' : 'transparent',
                      padding: '4px 8px',
                      borderRadius: '4px',
                      width: '100%'
                    }}
                    onClick={() => setActiveImage(item.id)}
                  >
                    <Image 
                      src={item.url} 
                      alt={item.name} 
                      width={40} 
                      height={40} 
                      preview={false}
                      style={{ borderRadius: '4px', objectFit: 'cover' }}
                    />
                    <div style={{ marginLeft: 8, flex: 1 }}>
                      <Text 
                        strong={activeImageId === item.id}
                        ellipsis={{ tooltip: item.name }}
                        style={{ width: '100%' }}
                      >
                        {item.name}
                      </Text>
                      {croppedImages[item.id] && (
                        <Text type="success" style={{ display: 'block', fontSize: '12px' }}>
                          已裁剪
                        </Text>
                      )}
                    </div>
                  </div>
                </List.Item>
              )}
            />
            
            {images.length > 0 && (
              <div style={{ marginTop: 16, textAlign: 'center' }}>
                <Button 
                  type="primary" 
                  icon={<DownloadOutlined />} 
                  onClick={handleDownloadAll}
                  disabled={Object.keys(croppedImages).length === 0}
                >
                  批量下载所有裁剪图片
                </Button>
              </div>
            )}
          </Card>
        </Col>
        
        <Col span={12}>
          <Card title="预览区域" size="small">
            {activeImage ? (
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                <div style={{ 
                  position: 'relative', 
                  width: '100%', 
                  height: 400, 
                  marginBottom: 20,
                  backgroundColor: '#fafafa'
                }}>
                  <Cropper
                    image={activeImage.url}
                    crop={crop}
                    zoom={zoom}
                    rotation={rotation}
                    aspect={cropSize.width / cropSize.height}
                    onCropChange={setCrop}
                    onZoomChange={setZoom}
                    onRotationChange={setRotation}
                    onCropComplete={onCropComplete}
                    cropShape="rect"
                    showGrid
                    // 添加对裁剪框尺寸变化的响应
                    cropSize={cropSize}
                  />
                </div>
                
                <div style={{ textAlign: 'center', width: '100%' }}>
                    <Title level={5}>{activeImage.name}</Title>
                    <Text type="secondary">选择裁剪区域并调整参数</Text>
                    <div style={{ marginTop: 10 }}>
                      <Space>
                        <Text>裁剪框大小: </Text>
                        <InputNumber 
                          value={cropSize.width} 
                          onChange={(value) => value && handleCropWidthChange(value)} 
                          min={50}
                          max={2000}
                          style={{ width: 100 }}
                        />
                        <Text>x</Text>
                        <InputNumber 
                          value={cropSize.height} 
                          onChange={(value) => value && handleCropHeightChange(value)} 
                          min={50}
                          max={2000}
                          style={{ width: 100 }}
                        />
                      </Space>
                    </div>
                  </div>
              </div>
            ) : (
              <div style={{ 
                height: 300, 
                display: 'flex', 
                justifyContent: 'center', 
                alignItems: 'center',
                border: '1px dashed #ccc'
              }}>
                <span>请先上传图片</span>
              </div>
            )}
          </Card>
        </Col>
      </Row>
    </Card>
  );
};

export default BatchImageCropper;